<template>
  <div>
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <WangEditor v-model="this.formData.content" @editorChange="editorChange"
                    :default-value="this.formData.content" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import AddImg from '@/components/PopItems/add-img.vue'
import WangEditor from '@/components/WangEditor/index.vue'

export default {
  name: 'AddEnergyCategory',
  mixins: [dictMixin],
  components: { WangEditor, AddImg },
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      isAdd: true,
      formData: {
        content: ''
      },
    }
  },
  computed: {
    rules() {
      return {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 50, message: '名称最长50字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.$set(this.formData, 'id', data.id)
        this.$set(this.formData, 'name', data.name)
        this.$set(this.formData, 'content', data.content)
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      this.submit(params)
    }
  },
  methods: {
    editorChange(value) {
      this.formData.content = value
      this.$refs.form.validateField(['content'], (errorMessage) => {
      })
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.miniProgramContent.update(params)
          if (Number(res.code) === 1000) {
            this.$message.success(`编辑成功！`)
            this.$emit('onFinish', 'miniProgramContent-add')
          }
        }
      })
    }
  }
}
</script>
